<template>
  <div class="login">
    <p class="title_p">
      <span>{{ t("home_page_login") }}</span>
      <iconpark-icon class="close" icon-id="exit" color="#fff" size="20px" @click="onClose"></iconpark-icon>
    </p>
    <div class="content">
      <div class="tab">
        <span v-shrink-on-click :class="state.active == i ? 'active_tab' : ''" v-for="(tab, i) in tabList" :key="i"
          @click="changeTab(i)">{{ t(tab.name) }}</span>
      </div>

      <div class="reg-box">
        <nut-form ref="formRef" label-position="top" :model-value="state.login" :rules="state.loginRules">
          <template v-for="(item, i) in state.loginList">
            <nut-form-item :label="t(item.label)" v-if="item.show" :rules="state.loginRules[item.name]"
              :prop="item.name" :key="i">
              <nut-input v-model="state.login[item.name]" :placeholder="t(item.placeholder)" :type="item.type"
                @blur="blurValidate(item.name)" clearable class="form_input">
                <!-- <template #left v-if="item.leftIcon">
                  <iconpark-icon :icon-id="item.leftIcon" color="#fff" size="1.5rem"></iconpark-icon>
                  <span v-if="item.name == 'cellphone'" style="color:#fff;margin-left: 5px;">+{{ state.codeValue
                    }}</span>
                </template> -->
                <template #right>
                  <div @click="iconClick(item)" v-if="state.login[item.name] !== '' && item.name === 'password'"
                    class="change_type_wrapper">
                    <iconpark-icon v-if="item.type == 'password'" name="hide" size="18px" />
                    <iconpark-icon v-if="item.type == 'text'" name="show" size="18px" />
                  </div>
                </template>

                <template v-if="item.name == 'captcha'" #right>
                  <div @click="refresh_captcha" class="btn">
                    <ImgT v-shrink-on-click :key="state.captchaURL" :src="state.captchaURL"
                      v-if="state.captchaURL && !state.captchaLoading" alt="captchaURL" />
                    <ImgT :class="{ loading_icon: state.captchaLoading }" v-if="state.captchaLoading"
                      style="width: 20px; height: 20px" :key="'level_icon_re'"
                      :src="'/imgs/level/level_icon_re.webp'" />
                  </div>
                </template>
              </nut-input>
            </nut-form-item>
          </template>
        </nut-form>
      </div>

      <div @click="checked = !checked" style="
          display: flex;
          align-items: center;
          justify-content: flex-start;
          color: #fff;
          font-size: 12px;
          font-weight: 400;
          position: relative;
          top: -5px;
          cursor: pointer;
        ">
        <img v-if="checked" style="width: 14px; height: 14px; margin-right: 4px" src="/imgs/login/checked.webp"
          alt="" />
        <img v-if="!checked" style="width: 14px; height: 14px; margin-right: 4px" src="/imgs/login/uncheck.webp"
          alt="" />
        <span style="font-weight: 400;">{{ t("home_page_rememberPassword") }}</span>
      </div>

      <div>
        <nut-button class="btn_block" :style="{ opacity: state.loading ? '0.5' : 1 }" round block
          @click="onLoginSubmit">
          {{ t("home_page_login") }}
        </nut-button>
      </div>
      <p class="set_password">
        <i @click="openReg">{{ t("home_page_noAccount") }}</i>
        <i @click="openForget">{{ t("home_page_forgetPassword") }}</i>
      </p>
    </div>
  </div>
  <!-- </div> -->
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";

import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";

import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import {
  verifyAccount,
  verifyCaptcha,
  verifyEmail,
  verifyMobile,
  verifyPassword,
} from "../utils/validateTools";
import { aaa, bbb, device_model, getDeviceId, getRandomSign } from "../net/Utils";

// import { showNotify } from "@nutui/nutui";
import { User } from "../store/user";
import pinia from "@/store/index";
// import { needLoginApi } from "@/utils/useNetMethods";
import { IP } from "@/utils/useStoreMethods";
import { Local } from "@/utils/storage";

const { t } = useI18n();
const checked = ref(true); // 记住密码

const router = useRouter();
const formRef = ref();
const route = useRoute();
const state: any = reactive({
  captchaURL: "",
  loading: false,
  captchaLoading: false,
  active: 0,
  formInitValue: null,
  rememberPassword: true,
  loginList: {
    phone: {
      name: "phone",
      label: "home_page_phone",
      type: "text",
      placeholder: "home_page_phone", //'home_page_enterPhoneNumber',
      slot: !1,
      leftIcon: false,
      changeRightIcon: !1 as any,
      show: !1,
      isPhone: true,
    },
    account: {
      name: "account",
      label: "home_page_account",
      type: "text",
      placeholder: "home_page_account", //'home_page_enterAccount',
      slot: !1,
      leftIcon: "signicon01",
      changeRightIcon: !1 as any,
      show: true,
    },
    email: {
      name: "email",
      label: "home_page_email",
      type: "text",
      placeholder: "home_page_email", //'home_page_enterEmail',
      slot: !1,
      leftIcon: "signicon05",
      changeRightIcon: !1 as any,
      show: false,
    },
    password: {
      name: "password",
      label: "home_page_password",
      type: "password",
      placeholder: "home_page_password", //'home_page_enterPassword',
      slot: !0,
      leftIcon: "signicon02",
      changeRightIcon: "hide" as any,
      show: !0,
    },
    captcha: {
      name: "captcha",
      label: "home_page_verificationCode",
      type: "text",
      placeholder: "home_page_verificationCode", // 'home_page_enterVerificationCode',
      slot: !0,
      leftIcon: "signicon03",
      changeRightIcon: !1 as any,
      show: !0,
    },
  },

  login: {
    captcha: "",
    userName: "",
    phone: "",
    account: "",
    email: "",
    password: "",
  },
  loginRules: {
    phone: [
      {
        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t("home_page_enterPhoneNumber"));
          } else if (verifyMobile(state.codeValue, value)) {
            return Promise.resolve();
          } else {
            return Promise.reject(t("home_page_phoneNumberFormatIncorrect"));
          }
        },
      },
    ],
    captcha: [
      {
        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t("home_page_enterVerificationCode"));
          } else if (verifyCaptcha(value)) {
            return Promise.resolve();
          } else {
            return Promise.reject(t("home_page_verificationCodeFormatIncorrect"));
          }
        },
      },
    ],
    email: [
      {
        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t("home_page_enterEmail"));
          } else if (verifyEmail(value)) {
            return Promise.resolve();
          } else {
            return Promise.reject(t("home_page_emailIncorrect"));
          }
        },
      },
    ],
    password: [
      {
        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t("home_page_enterPassword"));
          } else if (verifyPassword(value)) {
            return Promise.resolve();
          } else {
            return Promise.reject(t("home_page_passwordFormatIncorrect"));
          }
        },
      },
    ],
    account: [
      {
        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t("home_page_enterAccount"));
          } else if (verifyAccount(value)) {
            return true;
          } else {
            return Promise.reject(t("home_page_accountFormatIncorrect"));
          }
        },
      },
    ],
  },

  codeValue: "84",
  codeOptions: [
    // {
    //   label: '+63',
    //   value: '+63',
    // },
    {
      label: "84",
      value: "84",
    },
    // {
    //   label: '+86',
    //   value: '+86',
    // },
  ],
});
// 登录缓存
const setLocal = () => {
  if (Local.get("account") !== null || Local.get("email") !== null) {
    setTimeout(() => {
      if (state.active == 0) {
        state.login.account = Local.get("account");
        if (state.login.account) {
          state.login.password = Local.get("password");
        } else {
          state.login.password = "";
        }
      } else {
        state.login.email = Local.get("email");
        if (state.login.email) {
          state.login.password = Local.get("password");
        } else {
          state.login.password = "";
        }
      }
    }, 0);
  }
};
setLocal();
const tabList = [
  { name: "home_page_accountLogin", value: 1 },
  { name: "home_page_emailLogin", value: 2 },
];
const handleCaptchaReceive = (captcha: any) => {
  state.captchaLoading = false;
  state.captchaURL = captcha.url;
};
const blurValidate = (prop: string) => {
  formRef.value?.validate(prop).then();
};
let codeLoading: any = false
const refresh_captcha = async () => {
  if (codeLoading) return
  codeLoading = true
  setTimeout(() => {
    codeLoading = false
  }, 1000)
  const req_register_captcha = NetPacket.req_register_captcha();
  let id = await getDeviceId();
  req_register_captcha.sign = getRandomSign(id);
  req_register_captcha.aaa = aaa.toString();
  req_register_captcha.bbb = bbb;
  PKwebsocket.instance.send(req_register_captcha, false, {
    callbackName: "msg_notify_register_captcha",
    callback: handleCaptchaReceive,
  });
  state.captchaLoading = true;
};
const iconClick = (a: any) => {
  if (a.type == "password") {
    a.type = "text";
  } else {
    a.type = "password";
  }
};

const changeTab = (tabId: number) => {
  state.active = tabId;
  formRef.value?.reset();
  if (state.active == 1) {
    state.loginList.account.show = false;
    state.loginList.email.show = true;
  } else {
    state.loginList.account.show = true;
    state.loginList.email.show = false;
  }
  state.login = {
    captcha: "",
    userName: "",
    phone: "",
    account: "",
    email: "",
    password: "",
  };

  // 记住密码的逻辑
  if (checked.value) {
    setLocal();
  }
};
const onLoginSubmit = async () => {
  if (state.loading) return;
  formRef.value?.validate().then(async ({ valid, errors }: any) => {
    if (valid) {
      state.loading = true;
      const req_login = NetPacket.req_login();
      switch (state.active) {
        case 0:
          req_login.username = state.login.account;
          req_login.login_type = 4;
          break;
        case 1:
          req_login.username = state.login.email;
          req_login.login_type = 5;
          // req_login.username = state.codeValue + state.login.phone;
          break;
      }

      req_login.password = state.login.password;
      req_login.device_id = await getDeviceId();
      req_login.device_model = device_model;
      req_login.channel_id = Number(route.query.channel_id) || 123;
      req_login.aaa = aaa.toString();
      req_login.bbb = bbb;
      req_login.ip = await IP();
      req_login.captcha = state.login.captcha;
      PKwebsocket.instance.send(req_login, false, {
        callbackName: "msg_nodify_login",
        callback: loginSuccess,
      });
    } else {
      console.warn("error:", errors);
    }
  });
};
const loginSuccess = async (message: any) => {
  state.loading = false;
  setTimeout(() => {
    state.loading = false;
  }, 300);

  const last_user_id = localStorage.getItem("last_user_id");
  if (last_user_id != message.user_id) {
    // localStorage.setItem("readed_notice_ids", "[]");
  }
  localStorage.setItem("last_user_id", message.user_id);

  if (message.code == 4444) {
    return;
  }
  if (message.code == 1) {
    // if (message.message) {
    //   showNotify.success(t("home_page_loginSuccess"));
    // }
    if (checked.value) {
      Local.set("account", state.login.account);
      Local.set("email", state.login.email);
      Local.set("password", state.login.password);
    }
    if (!checked.value) {
      Local.remove("account");
      Local.remove("email");
      Local.remove("password");
    }
    await User(pinia).getUserLoginInfo(message);
    onClose();
    router.replace({ name: "home" });
  } else {
    refresh_captcha();
  }
};
const openForget = async () => {
  await User(pinia).setForget(true);
  onClose();
};
const openReg = async () => {
  await User(pinia).setLogin(false);
  setTimeout(() => {
    User(pinia).setReg(true);
  }, 300);
};
const onClose = async () => {
  await User(pinia).setLogin(false);
};
onMounted(async () => {
  refresh_captcha();
});
</script>

<style lang="scss" scoped>
@keyframes roll {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}

.login {
  border-radius: 16px;
  background: #131232;
  box-shadow: 0.5px 0.5px 1px 0px #2e296b inset;
  width: 347px;

  .loading_icon {
    animation: roll 1s linear infinite;
  }

  :deep(.nut-input-value) {
    border-radius: 8px;
    background: #1d1c3c;
    box-shadow: 0.5px 0.5px 1px 0px #333260 inset;
    height: 48px;
    line-height: 48px;
    padding: 0 14px;
  }

  :deep(.nut-form-item) {
    padding: 0 0 14px 0 !important;

    .nut-cell__title {
      display: none !important;
    }
  }

  :deep(.nut-cell-group__wrap) {
    box-shadow: none;
    margin: 0;
  }

  :deep(.nut-form-item__body__slots) {
    display: flex;
  }

  :deep(.nut-cell-group .nut-cell::after) {
    border: none;
  }

  :deep(.nut-form-item.error.line::before) {
    border: none;
  }

  :deep(.nut-input-right-box) {
    position: relative;
  }

  :deep(.input-text) {
    font-weight: normal;

    &::placeholder {
      color: #504f6f !important;
    }
  }

  .title_p {
    border-bottom: 0.5px solid #242352;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 16px;
    font-weight: 500;
    line-height: 16px;
    position: relative;

    .close {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20px;
      color: #fff;
      font-size: 20px;
    }
  }

  .content {
    padding: 24px 20px 32px 20px;

    .tab {
      width: 200px;
      margin: 0 auto 22px auto;
      display: flex;
      justify-content: space-around;
      align-items: center;
      border-radius: 8px;
      background: #0b0b23;

      >span {
        width: 100px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #504f6f;
        font-size: 14px;
        font-weight: 400;
      }

      .active_tab {
        border-radius: 8px;
        background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%);
        box-shadow: 0.5px 0.5px 1px 0px #9b9eff inset;
        color: #fff;
        font-weight: 500;
        margin: 2px 0;
      }
    }
  }

  .set_password {
    color: #5d69ff;
    font-size: 12px;
    line-height: 14px;
    display: flex;
    justify-content: space-between;
    margin-top: 16px;

    i {
      font-style: normal;
      cursor: pointer;
      text-decoration: underline;
    }
  }

  .btn {
    width: 108px;
    height: 44px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    align-items: center;
    border-radius: 8px !important;
    overflow: hidden;
    position: relative;
    left: 12px;
    background-color: #0f052a;

    >img {
      width: 100%;
      height: 100%;
    }
  }

  .btn_block {
    border-radius: 8px !important;
    background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%);
    box-shadow: 0.5px 0.5px 1px 0px #9b9eff inset;
    height: 44px;
    margin-top: 24px;
  }

  .change_type_wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 24px;
  }
}
</style>
